package com.lanou.bookstore.cart.web.servlet;

import com.lanou.bookstore.book.dao.BookDao;
import com.lanou.bookstore.book.domain.Book;
import com.lanou.bookstore.cart.domain.Cart;
import com.lanou.bookstore.cart.domain.CartItem;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet(name = "CartServlet", urlPatterns = "/cart.do")
public class CartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
         * 1. 得到车
         * 2. 得到条目（得到图书和数量）
         * 3. 把条目添加到车中
         */
        /*
         * 1. 得到车
         */
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        /*
         * 表单传递的只有bid和数量
         * 2. 得到条目
         *   > 得到图书和数量
         *   > 先得到图书的bid，然后我们需要通过bid查询数据库得到Book
         *   > 数量表单中有
         */
        String bid = request.getParameter("bid");
        Book book = new BookDao().load(bid);
        int count = Integer.parseInt(request.getParameter("count"));
        CartItem cartItem = new CartItem();
        cartItem.setBook(book);
        cartItem.setCount(count);
        //todo cart.add
        /*
         * 3. 把条目添加到车中
         */
        Map<String, CartItem> map = cart.getMap();
        map.put(bid,cartItem);


        request.getRequestDispatcher("/jsps/cart/list.jsp").forward(request, response);

    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
